import { defineStore } from 'pinia'
import { authService } from '../api'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || null,
    username: localStorage.getItem('username') || '',
    userPoints: parseInt(localStorage.getItem('userPoints') || '0'),
    isAuthenticated: !!localStorage.getItem('isLoggedIn'),
    settings: {
      emailNotification: false,
      smsNotification: false
    }
  }),
  
  getters: {
    getToken: (state) => state.token,
    getUserName: (state) => state.username,
    getPoints: (state) => state.userPoints,
  },
  
  actions: {
    async login(username, password) {
      try {
        const result = await authService.login({
          username,
          password
        })
        
        if (result.success) {
          if (!result.data) {
            return { success: false, error: '服务器返回数据结构不正确' }
          }
          
          const data = result.data || {};
          const userData = data.userData || {};
          const token = data.token || '';
          const points = data.points || 0;
          const userName = userData.username || username;
          
          if (!token) {
            return { success: false, error: '获取登录令牌失败' }
          }
          
          this.setUserData(token, userName, points)
          
          if (userData && userData.settings) {
            this.settings = { ...this.settings, ...userData.settings };
          }
          
          return { success: true }
        } else {
          if (result.isNetworkError) {
            return { 
              success: false, 
              error: '网络请求失败，可能是跨域(CORS)问题。请联系管理员。',
              isNetworkError: true 
            }
          }
          return { success: false, error: result.message || result.error || '登录失败，请检查账号密码' }
        }
      } catch (error) {
        console.error('登录失败:', error)
        return { success: false, error: '网络错误，请稍后重试' }
      }
    },
    
    async register(username, password) {
      try {
        const result = await authService.register({
          username,
          password
        })
        
        if (result.success) {
          return { success: true }
        } else {
          return { 
            success: false, 
            error: result.error || result.message || '注册失败',
            isUserExists: result.error?.includes('用户已存在') || result.message?.includes('用户已存在')
          }
        }
      } catch (error) {
        console.error('注册失败:', error)
        return { success: false, error: '网络错误，请稍后重试' }
      }
    },
    
    async getUserScore() {
      if (!this.token) return { success: false, error: '未登录' }
      
      try {
        const result = await authService.getUserScore()
        
        if (result.success) {
          const score = result.data?.score || 0
          this.updatePoints(score)
          return { success: true, score }
        }
        return { success: false, error: result.message || '获取积分失败' }
      } catch (error) {
        console.error('获取用户积分失败:', error)
        return { success: false, error: '网络错误，请稍后重试' }
      }
    },
    
    async getUserScoreAfterChat(maxRetries = 3, delayMs = 300) {
      if (!this.token) return { success: false, error: '未登录' }
      
      let retries = 0;
      const oldPoints = this.userPoints; // 记录旧积分值
      
      const attemptGetScore = async () => {
        try {
          const result = await authService.getUserScore()
          
          if (result.success) {
            const score = result.data?.score || 0
            this.updatePoints(score)
            
            // 计算积分变化（静默处理，不在控制台显示）
            const pointsDiff = oldPoints - score;
            
            return { 
              success: true, 
              score,
              oldPoints,
              pointsDiff
            }
          }
          
          // 如果请求成功但返回错误，检查是否需要重试
          if (retries < maxRetries) {
            retries++;
            console.log(`获取积分失败，重试第${retries}次...`)
            await new Promise(resolve => setTimeout(resolve, delayMs));
            return attemptGetScore();
          }
          
          return { success: false, error: result.message || '获取积分失败' }
        } catch (error) {
          // 如果出现网络错误，检查是否需要重试
          if (retries < maxRetries) {
            retries++;
            console.log(`获取积分失败，重试第${retries}次...`)
            await new Promise(resolve => setTimeout(resolve, delayMs));
            return attemptGetScore();
          }
          
          console.error('获取用户积分失败:', error)
          return { success: false, error: '网络错误，请稍后重试' }
        }
      };
      
      return attemptGetScore();
    },
    
    setUserData(token, username, points, refreshToken) {
      this.token = token
      this.username = username
      this.userPoints = points
      this.isAuthenticated = true
      
      localStorage.setItem('token', token)
      localStorage.setItem('username', username)
      localStorage.setItem('userPoints', points.toString())
      localStorage.setItem('isLoggedIn', 'true')
      
      // 保存refresh_token到localStorage
      if (refreshToken) {
        localStorage.setItem('refreshToken', refreshToken)
      }
    },
    
    logout() {
      this.token = null
      this.username = ''
      this.userPoints = 0
      this.isAuthenticated = false
      
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('username')
      localStorage.removeItem('userPoints')
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('rememberMe')
    },
    
    async rechargePoints(rechargeData) {
      if (!this.token) return { success: false, error: '未登录' }
      
      try {
        const result = await authService.rechargePoints(rechargeData)
        
        if (result.success) {
          // 更新积分余额
          const newPoints = result.data?.newPoints || this.userPoints + rechargeData.points
          this.updatePoints(newPoints)
          return { success: true, newPoints }
        }
        return { success: false, error: result.message || '充值失败' }
      } catch (error) {
        console.error('积分充值失败:', error)
        return { success: false, error: '网络错误，请稍后重试' }
      }
    },
    
    updatePoints(points) {
      this.userPoints = points
      localStorage.setItem('userPoints', points.toString())
    },
    
    subtractPoints(points) {
      this.userPoints -= points
      localStorage.setItem('userPoints', this.userPoints.toString())
    },
    
    updateSettings(newSettings) {
      this.settings = { ...this.settings, ...newSettings }
    },
    
    async signIn() {
      if (!this.token) return { success: false, error: '未登录' }
      
      try {
        const result = await authService.signIn()
        
        if (result.success) {
          // 签到成功，更新积分
          const addedScore = result.data?.added_score || 0
          this.userPoints += addedScore
          localStorage.setItem('userPoints', this.userPoints.toString())
          
          return { 
            success: true, 
            message: result.message || '签到成功', 
            addedScore 
          }
        } else if (result.alreadySigned) {
          // 今日已签到
          return { 
            success: false, 
            message: result.message || '今日已签到', 
            alreadySigned: true 
          }
        }
        
        return { 
          success: false, 
          message: result.message || '签到失败'
        }
      } catch (error) {
        console.error('签到失败:', error)
        return { success: false, error: '网络错误，请稍后重试' }
      }
    },
    
    async checkSignInStatus() {
      if (!this.token) return { success: false, error: '未登录', isSigned: false }
      
      try {
        console.log('userStore: 调用检查签到状态API');
        const result = await authService.checkSignInStatus()
        console.log('userStore: 收到检查签到状态结果', result);
        
        return {
          success: result.success,
          message: result.message,
          isSigned: result.isSigned
        }
      } catch (error) {
        console.error('userStore: 检查签到状态失败:', error)
        return { success: false, error: '网络错误，请稍后重试', isSigned: false }
      }
    }
  }
})